import React, { useEffect, useState } from 'react';
import { NavigationProp } from '@react-navigation/native';
import { ScrollView, StyleSheet } from 'react-native';
import { LinearProgress } from '@rneui/base';
import { CommonStyle } from '../common/commonStyle.ts';
import { WebView } from 'react-native-webview';

interface IWebViewScreenScreenProps {
  navigation: NavigationProp<any, 'webViewScreen'>;
  route: any;
}
function objectToQueryString(obj: Record<string, any>): string {
  return Object.keys(obj)
    .map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`)
    .join('&');
}
const WebViewScreen: React.FC<IWebViewScreenScreenProps> = ({ navigation, route }) => {
  const [loading, setLoading] = useState(true);
  const [uri, setUri] = useState<string | undefined>('');
  const [queryString, setQueryString] = useState<string | undefined>('');

  useEffect(() => {
    const { title } = route.params;
    navigation.setOptions({ title });
    const query = objectToQueryString(route.params.params);
    setQueryString(query || '');
    setUri(route.params.uri || '');
  }, []);

  return (
    <ScrollView contentContainerStyle={styles.container}>
      {loading && <LinearProgress color={CommonStyle.mainColor} />}
      {uri && <WebView source={{ uri: `${uri}?${queryString}` }} style={styles.webView} onLoad={() => setLoading(false)} />}
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: { flex: 1 },
  webView: { flex: 1 },
});
export default WebViewScreen;
